import { Dialog } from "@/hoc/Diolog";
import { renderForm } from "@/hoc/renderForm";
import apiStore from "@/stores/apiStore";
import { isSuccessCode, joinMicrotask, useGloablLoading } from "@Tea/utils";
import { PropType, Ref, defineComponent, reactive, watch } from "vue";
import { ElMessage }  from "element-plus"
import { PostionMemberParam } from "@Tea/model";

export type AddPositionForm =  {
  positionCode: string,
  positionName: string,
}
export type PostionDeatailTitleType = "新增成员"
export const PositionDetailsDialog = defineComponent({
  props: {
    visible: {
      type: Object as PropType<Ref<boolean>>,
      required: true,
    },
    title: {
      type: String as PropType<PostionDeatailTitleType>,
      required: true
    },
    ruleForm: {
      type: Object as PropType<PostionMemberParam>,
      default: {
        positionCode: '',
        userId: '',
      }
    },
    // 这里可以通过props 也可以 用 emiter
    handleSuccess: Function,
    handleFail: Function
  },
  setup(props, ctx) {
    const positionList = reactive([]) // 职位列表
    const userList = reactive([]) // 用户列表

    const { Form, submitForm, resetForm } = renderForm({
      ruleForm: props.ruleForm,
      content: [
        [
          {
            span: 24,
            label: "职位名称",
            type: "select",
            feild: "positionCode",
            option: positionList,
            attr: {
              placeholder:"请选择职位"
            }
          },
          {
            span: 24,
            label: "成员名称",
            type: "select",
            feild: "userId",
            option: userList,
            attr: {
              placeholder:"请选择成员"
            }
          }
        ]
      ],
      rules: {
        positionCode: [
          {
            required: true, message: '请选择职位', trigger: 'change',
          }
        ],
        userId: [
          {
            required: true, message: '请选择成员', trigger: 'change',
          }
        ],
      }
    });

    const { showLoading, closeLoading } = useGloablLoading()
    const { addPositionMember, getPositioList, addableList } = apiStore().api
    
    // 获取列表
    const getOptions = async function () {
      showLoading()
      try {
        const [p_res, u_res] = await Promise.all([
          getPositioList({ positionCode: "", positionName: "" }),
          addableList()
        ])
        if (isSuccessCode(p_res.code)) {
          positionList.push(...p_res.data.map((p) => ({
            label: p.positionName,
            value: p.positionCode
          })))
        }

        if (isSuccessCode(u_res.code)) {
          console.log(u_res.data);
          
          userList.push(...u_res.data.map((p) => ({
            label: p.username,
            value: p.userId
          })))
        }

        closeLoading()
      } catch (e) {
        console.log(e);
        closeLoading()
      }
    }

    watch(props.visible, (newVal) => {
      if (newVal) {
        Promise.resolve().then(() => {
          getOptions()
        })
      }
    })

    // 检验成功时，loading 由 dialog 维护
    const onSuccess = async function () {
      showLoading()
      try {
        const { code, msg } = await addPositionMember(props.ruleForm)
        closeLoading()
        if (isSuccessCode(code)) {
          ElMessage({
            message: msg,
            type: 'success',
          })
          props.handleSuccess?.()
        }
      } catch (e) {
        closeLoading()
      }
    }

    /**
     * @use 关闭时处理
     */
    const onClose = () => {
      // 清空请求到的数据列表
      positionList.length = 0
      userList.length = 0
      resetForm()
    }

    return () => (
      Dialog({
        visible: props.visible,
        title: props.title,
        width: "600px",
        content: Form,
        onConfirm: () => submitForm(onSuccess),
        onClose:()=> joinMicrotask(onClose)
      })
    )
  },
})